package com.zenchn.schedule.task;

import com.zenchn.entity.VisitCountBO;
import com.zenchn.enums.CommonStatusEnum;
import com.zenchn.enums.CustomerLevelTypeEnum;
import com.zenchn.enums.CustomerStatusEnum;
import com.zenchn.enums.CustomerTypeEnum;
import com.zenchn.model.*;
import com.zenchn.service.*;
import com.zenchn.utils.CommonUtils;
import com.zenchn.utils.SpringBeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户绩效完成情况 定时任务
 *
 * @author panbingqi
 * @date 2021-06-01
 */
@Component
public class CustomerCompletionTask implements Runnable {

    private Logger mLogger = LoggerFactory.getLogger(CustomerCompletionTask.class);

    @Override
    public void run() {
        try {
            mLogger.debug("用户绩效完成情况任务执行");
            System.out.println("-----------------");
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMM");

            AccountService accountService = SpringBeanUtil.getBean(AccountService.class);
            AccountExtendService accountExtendService = SpringBeanUtil.getBean(AccountExtendService.class);
            CustomerService customerService = SpringBeanUtil.getBean(CustomerService.class);
            CustomerUpgradeService customerUpgradeService = SpringBeanUtil.getBean(CustomerUpgradeService.class);
            CustomerVisitService customerVisitService = SpringBeanUtil.getBean(CustomerVisitService.class);
            CustomerCompletionService customerCompletionService = SpringBeanUtil.getBean(CustomerCompletionService.class);

            //获取用户业绩目标
            TSysAccountExample accountExample = new TSysAccountExample();
            accountExample.createCriteria().andStatusNotEqualTo(CommonStatusEnum.DELETE.getCode());

            List<String> accountList = accountService.selectByExample(accountExample).stream().map(TSysAccount::getAccountId).collect(Collectors.toList());
            if (accountList != null && !accountList.isEmpty()) {
                TMiAccountExtendExample accountExtendExample = new TMiAccountExtendExample();
                accountExtendExample.createCriteria().andAccountIdIn(accountList);

                List<TMiAccountExtend> accountExtendList = accountExtendService.selectByExample(accountExtendExample);
                if (accountExtendList != null && !accountExtendList.isEmpty()) {
                    //获取上个月开始时间
                    LocalDateTime startTime = LocalDateTime.of(LocalDate.now().minus(1, ChronoUnit.MONTHS).with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
                    //获取上个月结束时间
                    LocalDateTime endTime = LocalDateTime.of(LocalDate.now().minus(1, ChronoUnit.MONTHS).with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);
                    //获取上个月代理商绩效完成情况
                    Map<String, List<TMiCustomer>> agentTargetMap = getCustomerTarget(CustomerTypeEnum.AGENT.getType(), startTime, endTime, customerService);
                    //获取上个月代理商L2完成情况
                    Map<String, List<TMiCustomer>> agentL2CompletionMap = getUpgradeTarget(CustomerLevelTypeEnum.TWO.getType(), CustomerTypeEnum.AGENT.getType(), startTime, endTime, customerService, customerUpgradeService);
                    //获取上个月代理商L3完成情况
                    Map<String, List<TMiCustomer>> agentL3CompletionMap = getUpgradeTarget(CustomerLevelTypeEnum.THREE.getType(), CustomerTypeEnum.AGENT.getType(), startTime, endTime, customerService, customerUpgradeService);
                    //获取上个月医院绩效完成情况
                    Map<String, List<TMiCustomer>> hospitalCompletion = getCustomerTarget(CustomerTypeEnum.HOSPITAL.getType(), startTime, endTime, customerService);
                    //获取上个月医院L2完成情况
                    Map<String, List<TMiCustomer>> hospitalL2Completion = getUpgradeTarget(CustomerLevelTypeEnum.TWO.getType(), CustomerTypeEnum.HOSPITAL.getType(), startTime, endTime, customerService, customerUpgradeService);
                    //获取上个月医院L3完成情况
                    Map<String, List<TMiCustomer>> hospitalL3Completion = getUpgradeTarget(CustomerLevelTypeEnum.THREE.getType(), CustomerTypeEnum.HOSPITAL.getType(), startTime, endTime, customerService, customerUpgradeService);
                    for (TMiAccountExtend accountExtend : accountExtendList) {
                        //设置上个月时间
                        String month = fmt.format(LocalDateTime.now().minus(1, ChronoUnit.MONTHS));
                        //如果存在，则更新绩效完成记录
                        TMiCustomerCompletionExample customerCompletionExample = new TMiCustomerCompletionExample();
                        customerCompletionExample.createCriteria().andAccountIdEqualTo(accountExtend.getAccountId()).andMonthEqualTo(month);

                        List<TMiCustomerCompletion> customerCompletionList = customerCompletionService.selectByExample(customerCompletionExample);
                        if (customerCompletionList != null && !customerCompletionList.isEmpty()) {
                            TMiCustomerCompletion customerCompletion = customerCompletionList.get(0);
                            if (customerCompletion != null) {
                                customerCompletionService.deleteByPrimaryKey(customerCompletion.getCompletionId());
                            }
                        }
                        //设置用户绩效完成情况
                        TMiCustomerCompletion customerCompletion = new TMiCustomerCompletion();
                        customerCompletion.setCompletionId(CommonUtils.randomUUID());
                        customerCompletion.setAccountId(accountExtend.getAccountId());
                        customerCompletion.setMonth(month);
                        customerCompletion.setAgentTarget(accountExtend.getAgentTarget());
                        customerCompletion.setAgentL2Target(accountExtend.getAgentL2Target());
                        customerCompletion.setAgentL3Target(accountExtend.getAgentL3Target());
                        customerCompletion.setHospitalTarget(accountExtend.getHospitalTarget());
                        customerCompletion.setHospitalL2Target(accountExtend.getHospitalL2Target());
                        customerCompletion.setHospitalL3Target(accountExtend.getHospitalL3Target());
                        customerCompletion.setAgentCompletion(agentTargetMap.get(accountExtend.getAccountId()) == null ? 0 : agentTargetMap.get(accountExtend.getAccountId()).size());
                        customerCompletion.setAgentL2Completion(agentL2CompletionMap.get(accountExtend.getAccountId()) == null ? 0 : agentL2CompletionMap.get(accountExtend.getAccountId()).size());
                        customerCompletion.setAgentL3Completion(agentL3CompletionMap.get(accountExtend.getAccountId()) == null ? 0 : agentL3CompletionMap.get(accountExtend.getAccountId()).size());
                        customerCompletion.setHospitalCompletion(hospitalCompletion.get(accountExtend.getAccountId()) == null ? 0 : hospitalCompletion.get(accountExtend.getAccountId()).size());
                        customerCompletion.setHospitalL2Completion(hospitalL2Completion.get(accountExtend.getAccountId()) == null ? 0 : hospitalL2Completion.get(accountExtend.getAccountId()).size());
                        customerCompletion.setHospitalL3Completion(hospitalL3Completion.get(accountExtend.getAccountId()) == null ? 0 : hospitalL3Completion.get(accountExtend.getAccountId()).size());
                        customerCompletion.setCreator("00000000000000000000000000000000");
                        customerCompletion.setCreateTime(LocalDateTime.now());
                        //设置拜访记录数量
                        VisitCountBO customerVisit = customerVisitService.getCustomerVisit(startTime.toLocalDate(), endTime.plus(1,ChronoUnit.DAYS).toLocalDate(), accountExtend.getAccountId());
                        if (customerVisit != null) {
                            customerCompletion.setAgentVisit(customerVisit.getAgentVisit());
                            customerCompletion.setHospitalVisit(customerVisit.getHospitalVisit());
                        }

                        customerCompletionService.insert(customerCompletion);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            mLogger.error("用户绩效完成情况任务执行失败，原因:{}", e.getMessage());
        }
    }

    /**
     * 获取上个月客户绩效完成情况
     *
     * @param customerType
     * @param startTime
     * @param endTime
     * @param customerService
     * @return
     */
    private Map<String, List<TMiCustomer>> getCustomerTarget(String customerType, LocalDateTime startTime, LocalDateTime endTime, CustomerService customerService) {
        TMiCustomerExample customerExample = new TMiCustomerExample();
        TMiCustomerExample.Criteria criteria = customerExample.createCriteria();
        criteria.andCreateTimeGreaterThanOrEqualTo(startTime);
        criteria.andCreateTimeLessThanOrEqualTo(endTime);
        criteria.andCustomerTypeEqualTo(customerType);

        Map<String, List<TMiCustomer>> map = customerService.selectByExample(customerExample).stream().collect(Collectors.groupingBy(t -> t.getAccountId()));
        return map;
    }

    /**
     * 获取上个月客户升级记录情况
     *
     * @param level
     * @param customerType
     * @param startTime
     * @param endTime
     * @param customerService
     * @param customerUpgradeService
     * @return
     */
    private Map<String, List<TMiCustomer>> getUpgradeTarget(Integer level, String customerType, LocalDateTime startTime, LocalDateTime endTime, CustomerService customerService, CustomerUpgradeService customerUpgradeService) {
        Map<String, List<TMiCustomer>> map = new HashMap<>();
        TMiCustomerUpgradeExample customerUpgradeExample = new TMiCustomerUpgradeExample();
        TMiCustomerUpgradeExample.Criteria criteria = customerUpgradeExample.createCriteria();
        criteria.andCreateTimeGreaterThanOrEqualTo(startTime);
        criteria.andCreateTimeLessThanOrEqualTo(endTime);
        criteria.andUpgradeLevelEqualTo(level);
        criteria.andIsEnableEqualTo(CustomerStatusEnum.EFFECTIVE.getUpgradeStatus());

        List<String> customerIdList = customerUpgradeService.selectByExample(customerUpgradeExample).stream().map(TMiCustomerUpgrade::getCustomerId).collect(Collectors.toList());
        if (customerIdList != null && !customerIdList.isEmpty()) {
            TMiCustomerExample customerExample = new TMiCustomerExample();
            customerExample.createCriteria().andCustomerIdIn(customerIdList).andCustomerTypeEqualTo(customerType);

            map = customerService.selectByExample(customerExample).stream().collect(Collectors.groupingBy(t -> t.getAccountId()));
        }
        return map;
    }
}
